package ace.cmp.data.methodname.sql.mybatisplus.core.mysql.dml;

import ace.cmp.data.methodname.method.name.sql.core.enums.SqlCommandTypeEnum;
import ace.cmp.data.methodname.method.name.sql.core.util.StringUtils;
import ace.cmp.data.methodname.method.name.sql.entity.resolver.EntityMethodNameToQueryResolver;
import ace.cmp.data.methodname.sql.mybatisplus.core.properties.MybatisPlugMethodNameToSqlProperties;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.jdbc.SQL;

/**
 * @author caspar
 * @date 2023/2/24 9:05 mybatis plus 根据method推导sql
 */
public class MethodToSqlExistsMysqlBuilder extends AbstractMethodToDmlSqlBuilder {

  public MethodToSqlExistsMysqlBuilder(
      EntityMethodNameToQueryResolver queryResolver,
      TableInfo tableInfo,
      MybatisPlugMethodNameToSqlProperties sqlProperties) {
    super(queryResolver, tableInfo, sqlProperties);
  }

  @Override
  public String getSql() {
    SQL sqlBuilder = this.getSqlBuilder();
    sqlBuilder.SELECT(
        String.format(
            "COUNT(%s*)", this.getQueryResolver().getDistinct() ? "DISTINCT " : StringUtils.EMPTY));
    this.addSelectFrom();
    this.addFilters();
    sqlBuilder.LIMIT(1);
    return this.getSqlBuilder().toString();
  }

  @Override
  public Boolean getSupport() {
    return SqlCommandTypeEnum.EXISTS.equals(getQueryResolver().getSqlCommandType());
  }
}
